<template>
  <div class="chat-app">
    <div class="chat-container">
      <!-- 左侧聊天记录列表 -->
      <div class="chat-sidebar">
        <div class="sidebar-header">
          <h2>聊天记录</h2>
          <div class="header-actions">
            <el-button
                @click="createNewChat"
                circle
            >
              <img src="@/assets/aibirdicon/huihua.png" alt="创建新聊天" style="width: 100%">
            </el-button>
            <el-input
                v-model="searchKeyword"
                placeholder="搜索聊天记录..."
                clearable
                :prefix-icon="Search"
            />
          </div>
        </div>

        <div class="chat-list">
          <div
              v-for="chat in filteredChats"
              :key="chat.id"
              class="chat-item"
              :class="{ active: activeChatId === chat.id }"
              @click="selectChat(chat.id)"
          >
            <div class="avatar">
            </div>
            <div class="chat-info">
              <div class="name-time">
                <h3>{{chat.lastMessage }}</h3>
                <span class="time">{{ chat.lastTime }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天框 -->
      <div class="chat-main">
        <div class="chat-messages" ref="messagesContainer">
          <div
              v-for="(message, index) in activeChatMessages"
              :key="index"
              class="message"
              :class="message.sender"
          >
            <div class="message-content">
              <div v-if="message.type === 'text'" class="text-message">
                {{ message.content }}
                <el-tooltip content="复制消息" placement="top">
                  <el-button
                      class="copy-btn"
                      type="text"
                      @click="copyMessage(message.content)"
                  >
                    <img src="@/assets/aibirdicon/copy.png" alt="复制消息" style="width: 100%">
                  </el-button>
                </el-tooltip>
              </div>

              <div v-if="message.type === 'image'" class="image-message">
                <img :src="message.content" alt="发送的图片">
                <el-tooltip content="下载图片" placement="top">
                  <el-button
                      class="download-btn"
                      type="text"
                      @click="downloadImage(message.content)"
                  >
                    <img src="@/assets/aibirdicon/download.png" alt="下载图片" style="width: 100%">
                  </el-button>
                </el-tooltip>
              </div>

              <div class="message-time">
                {{ formatTime(message.time) }}
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <div class="input-actions">
            <el-upload
                action="#"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :http-request="sendImage"
                accept="image/*"
            >
              <el-button  circle>
                <img src="@/assets/aibirdicon/pictureup.png" alt="上传图片" style="width: 100%">
              </el-button>
            </el-upload>
          </div>

          <el-input
              v-model="newMessage"
              type="textarea"
              :rows="2"
              placeholder="输入消息..."
              resize="none"
              @keydown.enter.exact.prevent="sendTextMessage"
          ></el-input>

          <el-button
              :type="newMessage !== '' ? 'primary' : null"
              circle
              @click="sendTextMessage"
          >
            <img src="@/assets/aibirdicon/commit.png" alt="发送消息" style="width: 100%">
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {Search} from "@element-plus/icons-vue";


// 聊天数据
const chats = ref([
  {
    id: 1,
    name: '鸟类保护协会',
    avatar: 'https://via.placeholder.com/50/27ae60/ffffff?text=BP',
    lastMessage: '关于湿地保护区的最新监测报告已发送',
    lastTime: '10:30',
    online: true,
    messages: [
      { id: 1, type: 'text', content: '您好，这是最新的鸟类监测报告', sender: 'other', time: new Date(2023, 9, 15, 9, 30) },
      { id: 2, type: 'text', content: '收到，非常感谢！', sender: 'me', time: new Date(2023, 9, 15, 9, 32) },
      { id: 3, type: 'text', content: '关于湿地保护区的最新监测报告已发送', sender: 'other', time: new Date(2023, 9, 15, 10, 30) }
    ]
  },
  {
    id: 2,
    name: '张研究员',
    avatar: 'https://via.placeholder.com/50/3498db/ffffff?text=Z',
    lastMessage: '东方白鹳的迁徙数据已整理完成',
    lastTime: '昨天',
    online: false,
    messages: [
      { id: 1, type: 'text', content: '东方白鹳的迁徙数据已整理完成', sender: 'other', time: new Date(2023, 9, 14, 15, 45) },
      { id: 2, type: 'text', content: '太好了，我马上查看', sender: 'me', time: new Date(2023, 9, 14, 15, 50) }
    ]
  },
  {
    id: 3,
    name: '监测团队',
    avatar: 'https://via.placeholder.com/50/e74c3c/ffffff?text=MT',
    lastMessage: '本周监测计划已更新',
    lastTime: '周三',
    online: true,
    messages: [
      { id: 1, type: 'text', content: '本周监测计划已更新', sender: 'other', time: new Date(2023, 9, 11, 14, 20) },
      { id: 2, type: 'image', content: 'https://images.unsplash.com/photo-1551085254-e96b210db58a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=500&q=80', sender: 'other', time: new Date(2023, 9, 11, 14, 22) },
      { id: 3, type: 'text', content: '收到，我们会按照计划执行', sender: 'me', time: new Date(2023, 9, 11, 14, 25) }
    ]
  }
])

// 保存聊天数据到 localStorage
const saveChatData = () => {
  localStorage.setItem('chat-app-data', JSON.stringify(chats.value))
}

// 监听聊天数据变化并保存
watch(chats.value, () => {
  saveChatData()
}, { deep: true })

// 搜索关键词
const searchKeyword = ref('')

// 当前选中的聊天ID
const activeChatId = ref(1)

// 新消息内容
const newMessage = ref('')

// 消息容器引用
const messagesContainer = ref(null)

// 计算属性：过滤聊天列表
const filteredChats = computed(() => {
  if (!searchKeyword.value) return chats.value
  const keyword = searchKeyword.value.toLowerCase()
  return chats.value.filter(chat =>
      chat.name.toLowerCase().includes(keyword) ||
      chat.lastMessage.toLowerCase().includes(keyword)
  )
})

// 计算属性：当前选中的聊天
const activeChat = computed(() => {
  return chats.value.find(chat => chat.id === activeChatId.value)
})

// 计算属性：当前聊天的消息
const activeChatMessages = computed(() => {
  if (!activeChat.value) return []
  return activeChat.value.messages
})

// 选择聊天
const selectChat = (chatId) => {
  activeChatId.value = chatId
}

// 创建新聊天
const createNewChat = () => {
  // 生成唯一ID
  const newId = Math.max(...chats.value.map(c => c.id), 0) + 1

  // 创建新聊天对象
  const newChat = {
    id: newId,
    name: `新会话 ${newId}`,
    avatar: 'https://via.placeholder.com/50/3498db/ffffff?text=N',
    lastMessage: '开始新的对话',
    lastTime: '刚刚',
    online: true,
    messages: []
  }

  // 添加到聊天列表
  chats.value.unshift(newChat)

  // 切换到新聊天
  activeChatId.value = newId

  ElMessage.success('新会话已创建')
}

// 发送文本消息
const sendTextMessage = () => {
  if (!newMessage.value.trim()) return

  const chat = chats.value.find(c => c.id === activeChatId.value)
  if (chat) {
    const newMsg = {
      id: Date.now(),
      type: 'text',
      content: newMessage.value.trim(),
      sender: 'me',
      time: new Date()
    }

    chat.messages.push(newMsg)
    chat.lastMessage = newMessage.value.trim()
    chat.lastTime = '刚刚'

    newMessage.value = ''

    // 模拟对方回复
    setTimeout(() => {
      const replyMsg = {
        id: Date.now() + 1,
        type: 'text',
        content: '收到您的消息，我们会尽快处理',
        sender: 'other',
        time: new Date()
      }

      chat.messages.push(replyMsg)
      chat.lastMessage = replyMsg.content
      chat.lastTime = '刚刚'

      scrollToBottom()
    }, 2000)
  }

  scrollToBottom()
}

// 发送图片消息
const sendImage = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const chat = chats.value.find(c => c.id === activeChatId.value)
    if (chat) {
      const newMsg = {
        id: Date.now(),
        type: 'image',
        content: e.target.result,
        sender: 'me',
        time: new Date()
      }

      chat.messages.push(newMsg)
      chat.lastMessage = '[图片]'
      chat.lastTime = '刚刚'

      scrollToBottom()
    }
  }
  reader.readAsDataURL(file.file)
}

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }

  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }

  return true
}

// 滚动到消息底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (date) => {
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 复制消息功能
const copyMessage = (content) => {
  // 创建一个临时的textarea元素
  const textarea = document.createElement('textarea')
  textarea.value = content
  document.body.appendChild(textarea)

  // 选择文本
  textarea.select()

  try {
    // 尝试使用现代API
    if (navigator.clipboard) {
      navigator.clipboard.writeText(content)
          .then(() => {
            ElMessage.success('已复制到剪贴板')
          })
          .catch(err => {
            console.error('复制失败:', err)
            ElMessage.error('复制失败')
          })
    } else {
      // 回退到document.execCommand
      const success = document.execCommand('copy')
      if (success) {
        ElMessage.success('已复制到剪贴板')
      } else {
        ElMessage.error('复制失败')
      }
    }
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败')
  } finally {
    // 清理临时元素
    document.body.removeChild(textarea)
  }
}

// 下载图片功能
const downloadImage = (imageData) => {
  try {
    // 创建一个临时的a标签
    const link = document.createElement('a')
    link.href = imageData

    // 设置下载文件名
    const timestamp = new Date().getTime()
    link.download = `bird-image-${timestamp}.png`

    // 添加到文档并触发点击
    document.body.appendChild(link)
    link.click()

    // 清理
    document.body.removeChild(link)

    ElMessage.success('图片下载成功')
  } catch (error) {
    console.error('下载图片失败:', error)
    ElMessage.error('下载图片失败')
  }
}

// 初始化时滚动到底部
onMounted(() => {
  scrollToBottom()

  // 加载聊天数据
  const savedData = localStorage.getItem('chat-app-data')
  if (savedData) {
    try {
      const parsedData = JSON.parse(savedData)

      // 恢复日期对象
      parsedData.forEach(chat => {
        chat.messages.forEach(msg => {
          msg.time = new Date(msg.time)
        })
      })

      chats.value = parsedData
    } catch (e) {
      console.error('Failed to parse chat data:', e)
      localStorage.removeItem('chat-app-data')
    }
  }
})

// 当活动聊天变化时滚动到底部
watch(activeChatId, () => {
  scrollToBottom()
})

// 添加定期保存功能
setInterval(saveChatData, 30000) // 每30秒保存一次
</script>

<style scoped>
.chat-app {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  background: linear-gradient(135deg, #e0f7fa, #c8e6c9, #a5d6a7);
}

.chat-container {
  display: flex;
  width: 80%;
  height: 85vh;
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  margin: 0 auto;
}

/* 左侧聊天记录样式 */
.chat-sidebar {
  width: 30%;
  border-right: 1px solid #eaeaea;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #eaeaea;
  background: white;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.sidebar-header h2 {
  font-size: 20px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 10px;
}

.sidebar-header h2 i {
  color: #27ae60;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.chat-item {
  display: flex;
  padding: 15px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 10px;
}

.chat-item:hover {
  background: #e9ecef;
}

.chat-item.active {
  background: #e3f2fd;
}

.avatar {
  position: relative;
  margin-right: 15px;
}

.avatar img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.chat-info {
  flex: 1;
  min-width: 0;
}

.name-time {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.name-time h3 {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.name-time .time {
  font-size: 12px;
  color: #95a5a6;
  flex-shrink: 0;
}

/* 右侧聊天框样式 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
}

.contact-info .avatar {
  margin-right: 15px;
}

.contact-info .info h2 {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 3px;
}

.contact-info .info p {
  font-size: 14px;
}

.contact-info .online {
  color: #27ae60;
}

.contact-info .offline {
  color: #95a5a6;
}

.header-actions .el-button {
  margin-left: 10px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.message {
  display: flex;
  margin-bottom: 20px;
}

.message.me {
  justify-content: flex-end;
}

.message.other {
  justify-content: flex-start;
}

.message-content {
  position: relative;
  max-width: 70%;
  padding: 12px 15px;
  border-radius: 18px;
}

.message.me .message-content {
  background: #d1e7ff;
  border-top-right-radius: 5px;
}

.message.other .message-content {
  background: white;
  border-top-left-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.text-message {
  position: relative;
  font-size: 15px;
  line-height: 1.5;
  color: #2c3e50;
  padding-right: 25px;
}

.message.me .text-message {
  padding-right: 0;
  padding-left: 25px;
}

.image-message {
  position: relative;
  display: inline-block;
}

.image-message img {
  max-width: 300px;
  max-height: 300px;
  border-radius: 10px;
  display: block;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.image-message img:hover {
  transform: scale(1.03);
}

.message-time {
  font-size: 11px;
  color: #95a5a6;
  text-align: right;
  margin-top: 5px;
}

/* 复制按钮样式 */
.copy-btn {
  width: 30px;
  height: 30px;
  transition: opacity 0.3s ease;
  padding: 4px;
  z-index: 10;
}

.message.me .copy-btn {
  right: auto;
  left: 5px;
}

.text-message:hover .copy-btn {
  opacity: 1;
}

/* 下载按钮样式 */
.download-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 30px;
  height: 30px;
  transition: opacity 0.3s ease;
  border-radius: 50%;
  padding: 4px;
  z-index: 10;
}

.message.me .download-btn {
  right: auto;
  left: 5px;
}

.image-message:hover .download-btn {
  opacity: 1;
}

.chat-input {
  padding: 15px;
  background: white;
  border-top: 1px solid #eaeaea;
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

.input-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.input-actions .el-button {
  margin: 0;
}

.chat-input .el-textarea {
  flex: 1;
}

.chat-input .el-button {
  height: 40px;
  width: 40px;
}
</style>

<style>
/* 覆盖Element Plus样式 */
.chat-input .el-textarea__inner {
  border: none;
  background: #f8f9fa;
  border-radius: 20px;
  padding: 10px 15px;
  box-shadow: none;
}

.chat-input .el-textarea__inner:focus {
  box-shadow: none;
}

.chat-input .el-button {
  background: #f8f9fa;
  border: none;
}

.chat-input .el-button--primary {
  background: #27ae60;
  color: white;
}

.chat-input .el-button--primary:hover {
  background: #219653;
}
</style>